import { get as getVal } from "svelte/store";
import { currentDataset$, userDatasets$, syncToUserDatasets, currentListDatasetParam$, type CreateDatasetParam, type UpdateDatasetParam } from "@store/entity/dataset";
import { createDataset, updateDataset, listDatasets, getDataset } from "@api/dataset";


export const create = async (val: CreateDatasetParam) => {
  await createDataset(val);
  await loadingDatasets();
};

export const update = async (val: UpdateDatasetParam) => {
  await updateDataset(val);
  await loadingDatasets();
};

export const loadingDatasets = async () => {
  const datasets = await listDatasets(getVal(currentListDatasetParam$));
  console.log('set userDatasets$=>', datasets)
  userDatasets$.set(datasets);
};

export const loadingByCode = async (code: string) => {
  const dataset = await getDataset(code)
  syncToUserDatasets(dataset);
}

export const renameCurrentDataset = async (newName: string) => {
  const { id, name } = getVal(currentDataset$);
  if (newName === name) {
    console.warn("new name no changes");
    return;
  }
  const $userDatasets$ = getVal(userDatasets$);
  const hasSameName =
    $userDatasets$.find((v) => v.id !== id && v.name === newName) !== undefined;
  if (hasSameName) {
    console.warn("new name is same with others");
    return;
  }
  await updateDataset({ id, name: newName });
  await loadingDatasets();
};

export const updateCurrentDatasetDesc = async (newDesc: string) => {
  const { id, desc } = getVal(currentDataset$)!;
  if (newDesc === desc) {
    console.warn("new desc no changes");
    return;
  }
  await updateDataset({ id, desc: newDesc });
  await loadingDatasets();
};
